
package http.file.rbt;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.SystemPropertyUtil;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpFileDownServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private static final Pattern RANGE_DATA = Pattern.compile("[0-9]*-[0-9]*");
    private FullHttpRequest request;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        this.request = request;
        //判断http解码是否成功
        if (!request.decoderResult().isSuccess()) {
            sendText(ctx, BAD_REQUEST,"请求失败");
            return;
        }
        //必须是get方法
        if (!GET.equals(request.method())) {
            sendText(ctx, METHOD_NOT_ALLOWED,"只支持"+GET.name()+"方法");
            return;
        }
        final boolean keepAlive = HttpUtil.isKeepAlive(request);
        final String uri = request.uri();//获取request的url,这里获取的相对路径
        final String path = urlToLocalPath(uri);
        if (path == null) {
            sendText(ctx, FORBIDDEN,"路径错误");
            return;
        }
        File file = new File(path);
        if (file.isHidden() || !file.exists()) {
            sendText(ctx, NOT_FOUND,"文件不存在");
            return;
        }
        if (!file.isFile()) {
            sendText(ctx, FORBIDDEN,"请求的不是一个文件");
            return;
        }
        String range = request.headers().get(HttpHeaderNames.RANGE);
        if (range == null || range.isEmpty()) {
            sendAccept(ctx,OK,file.length());
        }
        if(!RANGE_DATA.matcher(range).matches()){
            sendText(ctx,FORBIDDEN,"请求头的Range格式不对");
        }
        String[] rangeVal=range.split("-");
        long start=rangeVal[0]==null||rangeVal[0].equals("")?-1:Long.valueOf(rangeVal[0]);
        long end=rangeVal[1]==null||rangeVal[1].equals("")?-1:Long.valueOf(rangeVal[1]);
        if(start<0&&end<0){
            sendText(ctx,FORBIDDEN,"请求头的Range格式不对");
        }

        //走到说明要发送文件给浏览器了
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (FileNotFoundException ignore) {
            sendText(ctx, NOT_FOUND,"文件不存在");
            return;
        }
        long fileLength = raf.length();//文件长度
        if(start>fileLength||end>fileLength){
            sendText(ctx,FORBIDDEN,"请求数据大小超过文件大小");
        }
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, PARTIAL_CONTENT);
        HttpUtil.setContentLength(response, fileLength);
        //设置reponse的connection:close或connection:keep-alive
        if (!keepAlive) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        } else if (request.protocolVersion().equals(HTTP_1_0)) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        //向浏览器发送头部消息
        ctx.write(response);
        //发送文件
        ChannelFuture sendFileFuture;
        ChannelFuture lastContentFuture;
        long pos=0;
        long lengthByte=0;
        if(start>=0&&end<0){
            pos=start;
            lengthByte=fileLength-pos+1;
        }
        if(end>=0&&start<0){
            pos=fileLength-1-end;
            lengthByte=end;
        }
        if(start>=0&&end>=0){
            pos=start;
            lengthByte=end-start+1;
        }
        sendFileFuture =
                ctx.write(new DefaultFileRegion(raf.getChannel(), pos, lengthByte), ctx.newProgressivePromise());
        //手动发送结束表示
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

        sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
                if (total < 0) {
                    System.err.println(future.channel() + "数据传输进度" + progress);
                } else {
                    System.err.println(future.channel() + "数据传输进度 " + progress + " / " + total);
                }
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) {
                System.err.println(future.channel() + " 数据传输结束");
            }
        });
        //根据是否长连接判断是否要关闭浏览器和服务器建立的连接
        if (!keepAlive) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendText(ctx, INTERNAL_SERVER_ERROR,cause.getMessage());
        }
    }
    private static String urlToLocalPath(String uri) {
        try {
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }

        if (uri.isEmpty() || uri.charAt(0) != '/') {
            return null;
        }
        //本地分割符号替换url中的 '/'
        uri = uri.replace('/', File.separatorChar);
        // 返回文件的本地绝对路径
        return SystemPropertyUtil.get("user.dir") + File.separator + uri;
    }

    private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[^-\\._]?[^<>&\\\"]*");

    private void sendListing(ChannelHandlerContext ctx, File dir, String dirPath) {
        StringBuilder buf = new StringBuilder()
                .append("<!DOCTYPE html>\r\n")
                .append("<html><head><meta charset='utf-8' /><title>")
                .append("Listing of: ")
                .append(dirPath)
                .append("</title></head><body>\r\n")

                .append("<h3>Listing of: ")
                .append(dirPath)
                .append("</h3>\r\n")

                .append("<ul>")
                .append("<li><a href=\"../\">..</a></li>\r\n");

        File[] files = dir.listFiles();
        if (files != null) {
            for (File f: files) {
                if (f.isHidden() || !f.canRead()) {
                    continue;
                }

                String name = f.getName();
                if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
                    continue;
                }

                buf.append("<li><a href=\"")
                        .append(name)
                        .append("\">")
                        .append(name)
                        .append("</a></li>\r\n");
            }
        }

        buf.append("</ul></body></html>\r\n");

        ByteBuf buffer = ctx.alloc().buffer(buf.length());
        buffer.writeCharSequence(buf.toString(), CharsetUtil.UTF_8);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");

        replayMessage(ctx, response);
    }

    private void sendText(ChannelHandlerContext ctx, HttpResponseStatus status,String text) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, status, Unpooled.copiedBuffer(text + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        replayMessage(ctx, response);
    }
    private void sendAccept(ChannelHandlerContext ctx, HttpResponseStatus status,long fileSize) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1, status);
        response.headers().set(HttpHeaderNames.ACCEPT_RANGES, "bytes");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, fileSize);
        replayMessage(ctx, response);
    }
    private void replayMessage(ChannelHandlerContext ctx, FullHttpResponse response) {
        final FullHttpRequest request = this.request;
        final boolean keepAlive = HttpUtil.isKeepAlive(request);//判断是否是长链接
        HttpUtil.setContentLength(response, response.content().readableBytes());
        if (!keepAlive) {
            //不是长链接返回头设置：connection:close
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        } else if (request.protocolVersion().equals(HTTP_1_0)) {
            //长链接返回头设置：connection:keep-alive
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        //向客户端推送消息
        ChannelFuture flushPromise = ctx.writeAndFlush(response);
        if (!keepAlive) {
            //不是长链接，设置关闭监听器，返回给客户端信息结束后关闭连接
            flushPromise.addListener(ChannelFutureListener.CLOSE);
        }
    }

}
